<script setup lang="ts">
import useBiliStore from "@/store/modules/useBiliStore";
import { playAudio } from "@/views/utils/audio";

const biliStore = useBiliStore();
const setting = biliStore.songPlugin.config;
const songList = reactive([]);
onBeforeUnmount(() => {
  window.$bus.off("blive:Danmu", onBliveDanmu);
});
init();

function onBliveDanmu(val) {
  //console.log('Danmu:',val);
  const arr = [...val.content.matchAll(/点歌 (.+) (.+)/g)][0];
  if (!arr) return;
  const song = setting.songs.find(v => {
    if (!v.name.includes(arr[1])) return false;
    if (!v.author.includes(arr[2])) return false;
    return true;
  });
  if (song && songList.findIndex(v => v.path == song.path) == -1) {
    songList.push(song);
    playSongList();
  }
}
let isPlaying = false;
function playSongList() {
  if (!isPlaying && songList.length > 0) {
    isPlaying = true;
    playAudio(songList[0].path).then(() => {
      isPlaying = false;
      songList.shift();
      playSongList();
    });
  }
}
function init() {
  window.electronAPI.setTitle("点歌姬");
  window.electronAPI.removeAllEvent("blive:[Danmu]");
  window.electronAPI.removeAllEvent("blive:[Gift]");
  window.electronAPI.removeAllEvent("blive:[GuardBuy]");
  window.electronAPI.removeAllEvent("blive:[UserAction]");
  window.electronAPI.removeAllEvent("blive:[Open]");
  window.electronAPI.removeAllEvent("blive:[Close]");
  window.electronAPI.addBliveEvent("Danmu", (event, value) => {
    window.$bus.emit("blive:Danmu", value);
  });
  window.$bus.on("blive:Danmu", onBliveDanmu);
}
</script>

<template>
  <div v-if="setting.songs.length" class="h-screen overflow-scroll">
    <div v-if="songList.length" class="py-2 px-1 space-y-1">
      <div
        v-for="(item, idx) in songList"
        :key="idx"
        class="px-4 py-2 border-1 border-solid border-gray-200"
      >
        {{ item.author }} - {{ item.name }}
      </div>
    </div>
    <n-empty v-else class="mt-20" description="无人排队"></n-empty>
  </div>
</template>

<style scoped lang="scss"></style>

<route>
{
  meta: {
    layout: "default"
  }
}
</route>
